<?php
/**
 * Created by PhpStorm.
 * User: Administrator
 * Date: 2018/12/24/024
 * Time: 10:47
 */
namespace App\Validator;

use App\Http\Common\Lib\Common;
use Illuminate\Support\Facades\Validator;
//use Illuminate\Validation\Rules;

class BaseValidate extends Validator
{
    protected $input;
    protected $rules = [];
    protected $messages = [];
    protected $scenes = [];

    /**
     * 表单场景验证
     * @param $inputs
     * @param $scene
     * @return array
     */
    public function checkInput($inputs,$scene){
        $input = $this->getInputs($inputs,$scene);
        $rule = $this->getRules($scene);
        $messages = $this->getMessages($rule);
        $validator = Validator::make($input,$rule,$messages);
        if($validator->fails()){
            return Common::dataFormat(config('statusInfo.status.noPass'),$validator->errors()->first());
        }
        return Common::dataFormat(config('statusInfo.status.success'),config('statusInfo.msg.success'));
    }
    /**
     * 获取验证数据
     * @param $inputs
     * @param $scene
     * @return array
     */
    public function getInputs($inputs,$scene){
        $input = [];
        if(!$this->hasScene($scene)){
            return array_keys($this->rules);
        }
        foreach ($this->scenes[$scene] as $key=>$value){
            if(array_key_exists($value,$inputs)){
                $input[$value] = $inputs[$value];
            }
        }
        return $input;
    }

    /**
     * 获取验证规则
     * @param $scene
     * @return array
     */
    public function getRules($scene){
        $rule = [];
        if(!$this->hasScene($scene)){
            return $this->rules;
        }
        foreach ($this->scenes[$scene] as $key=>$value){
            if(array_key_exists($value,$this->rules)){
                $rule[$value] = $this->rules[$value];
            }

        }
        return $rule;
    }

    /**
     * 获取规则对应提示信息
     * @param $rules
     * @return array
     */
    public function getMessages($rules){
        $message = [];
        foreach ($rules as $key=>$value){
            $arr = explode('|',$value);
            foreach ($arr as $k1=>$v1){
                if(strpos($v1,':')){
                    unset($arr[$k1]);
                    $arr[] = substr($v1,0,strpos($v1,':'));
                }
            }
            foreach ($arr as $k2=>$v2){
                if(array_key_exists($key.'.'.$v2,$this->messages)){
                    $message[$key.'.'.$v2] = $this->messages[$key.'.'.$v2];
                }
            }
        }
        if(empty($message)){
            $message = $this->messages;
        }
        return $message;
    }

    /**
     * 检查有无对应的场景
     * @param $scene
     * @return bool
     */
    public function hasScene($scene){
        if(isset($this->scenes[$scene])){
            return true;
        }
        return false;
    }
}